import focusTabs from '../../consts/focusTabs';
import widgetTypes from '../../consts/widgetTypes';
import * as API from '../../services/Editor/widgets';

export default {
    namespace: 'widgets',
    state: [],
    reducers: {
        addWidgetsOfPage(oldWidgets, { payload: pWidgets }) {
            const widgets = oldWidgets.concat(pWidgets);
            return widgets;
        },
        clear() {
            return [];
        },
        removeWidget(oldWidgets = [], { payload: widget }) {
            const tWidgets = oldWidgets.filter(w => w.widget_id === widget.widget_id);
            if (tWidgets.length > 0) {
                const index = oldWidgets.indexOf(tWidgets[0]);
                oldWidgets[index].delFlag = true;
                return [...oldWidgets];
            }
            return oldWidgets;
        },
        removeWidgets(oldWidgets = [], { payload: widgets }) {
            const widgetsIds = widgets.map(w => w.widget_id);
            const newWidgets = oldWidgets.map((w) => {
                if (widgetsIds.indexOf(w.widget_id) !== -1) {
                    w.delFlag = true;
                }
                return w;
            });
            return [...newWidgets];
        },
        resetWidgets(oldWidgets = [], { payload: widgets }) {
            return [...widgets];
        },
        save(oldWidgets, { payload: pWidgets }) {
            return [...pWidgets];
        },
    },
    effects: {
        /**
         * 创建组件
         */
        *addWidget({ payload }, { select, call, put }) {
            const { pageId, widget, batch } = payload;
            const widgets = yield select(state => state.widgets);
            const sameTypeWidgets = widgets.filter(w => w.type === widget.type);
            // 第一步 赋初始值
            const initAttr = {}; // 预留接口，暂未实现
            const newWidget = { ...widget, initAttr };
            // 第二步 判断是否可以新增
            if (newWidget.onlyWidget && sameTypeWidgets.length > 1) {
                return;
            }
            // 第三步 调整显示位置和一些自增值
            if (widget.form_system) {
                newWidget.offset_x = widget.offset_x + 10;
                newWidget.offset_y = widget.offset_y + 10;
            }
            newWidget.sort = widgets.length + 1;
            newWidget.offset_z = widgets.length + 1;
            newWidget.id = null;
            newWidget.widget_id = null;
            // 第四步 修改名称
            if (!widget.form_system) {
                if (!newWidget.onlyWidget) {
                    newWidget.type_display += sameTypeWidgets.filter(w => !w.from_system).length + 1;
                }
            } else {
                const oldTypeDisplay = widget.label;
                let typeDisplay;
                const copy = oldTypeDisplay.split('copy');
                if (oldTypeDisplay.indexOf('copy') > -1) {
                    let count = Math.round(copy[copy.length - 1]) || 0;
                    count += 1;
                    typeDisplay = `${oldTypeDisplay.split('copy')[0]}copy${count}`;
                } else typeDisplay = `${oldTypeDisplay}copy`;
                newWidget.label = typeDisplay;
            }
            // 第五步 新增
            const { data } = yield call(API.create, pageId, newWidget);
            if (data) {
                data.page_id = pageId;
                data.widget_id = data.id;
                yield put({
                    type: 'addWidgetsOfPage',
                    payload: [data],
                });
            }
            // 第六步 选中
            if (!batch) {
                yield put({
                    type: 'selectWidget',
                    payload: data,
                });
            }
            return data;
        },
        *selectWidgetsByIds({ payload: widgetIds }, { put, select }) {
            const widgets = yield select(state => state.widgets);
            const selectedWidgets = widgets.filter(w => widgetIds.indexOf(w.widget_id) !== -1);
            yield put({
                type: 'selectWidgets',
                payload: selectedWidgets,
            });
        },
        /**
         * 选中某个组件
         */
        *selectWidget({ payload: widget }, { put }) {
            // 获取focusTab值
            let focusTab = focusTabs.PROPERTY;
            switch (widget.type) {
            case widgetTypes.REDBAG:
                focusTab = focusTabs.REDBAG;
                break;
            case widgetTypes.FIXEDBTN:
                focusTab = focusTabs.FIXEDBTN;
                break;
            case widgetTypes.LOOKERS:
                focusTab = focusTabs.LOOKERS;
                break;
            case widgetTypes.HOPEBANK:
                focusTab = focusTabs.HOPEBANK;
                break;
            default:
                focusTab = focusTabs.PROPERTY;
                break;
            }
            // 修改特定值
            yield put({
                type: 'editor/setState',
                payload: {
                    selectedWidgetIds: [widget.widget_id],
                    selectedWidgetId: widget.widget_id,
                    focusTab,
                    selectedWidget: widget,
                    selectedWidgets: [widget],
                },
            });
        },
        /**
         * 选中多个组件
         */
        *selectWidgets({ payload: widgets }, { put }) {
            // 获取focusTab值
            let focusTab = focusTabs.ALIGNMENT;

            if (widgets.length === 1) {
                switch (widgets[0].type) {
                case widgetTypes.REDBAG:
                    focusTab = focusTabs.REDBAG;
                    break;
                case widgetTypes.FIXEDBTN:
                    focusTab = focusTabs.FIXEDBTN;
                    break;
                case widgetTypes.LOOKERS:
                    focusTab = focusTabs.LOOKERS;
                    break;
                case widgetTypes.HOPEBANK:
                    focusTab = focusTabs.HOPEBANK;
                    break;
                default:
                    focusTab = focusTabs.PROPERTY;
                    break;
                }
            }

            if (widgets.length === 0) {
                focusTab = focusTabs.PAGE;
            }

            // 修改特定值
            yield put({
                type: 'editor/setState',
                payload: {
                    selectedWidgetIds: widgets.map(w => w.widget_id),
                    selectedWidgetId: widgets.length === 1 ? widgets[0].widget_id : null,
                    focusTab,
                    selectedWidget: widgets.length === 1 ? widgets[0] : null,
                    selectedWidgets: widgets,
                },
            });
        },
        *toggleWidgetVisible({ payload }, { put }) {
            yield put({
                type: 'updateWidget',
                payload: {
                    widget_id: payload.widgetId,
                    visible: payload.visible,
                },
            });
        },
        *toggleWidgetsVisible({ payload }, { put }) {
            const widgets = [];
            for (let i = 0; i < payload.widgetIds.length; i++) {
                const widgetId = payload.widgetIds[i];
                widgets.push({
                    widget_id: widgetId,
                    visible: payload.visible,
                });
            }
            yield put({
                type: 'updateWidgets',
                payload: widgets,
            });
        },
        *updateWidget({ payload: widget }, { select, call, put }) {
            const oldWidgets = yield select(state => state.widgets);
            const editor = yield select(state => state.editor);
            const sWidgets = oldWidgets.filter(w => w.widget_id === widget.widget_id);
            if (sWidgets.length > 0) {
                const sIndex = oldWidgets.indexOf(sWidgets[0]);
                const tWidget = { ...sWidgets[0], ...widget, timestamp: Math.round(new Date().valueOf() / 1000) + Math.random() };
                oldWidgets[sIndex] = tWidget;
            }
            yield put({
                type: 'save',
                payload: oldWidgets,
            });
            // 更新selselectedWidget 和 selectedWidgets
            if (editor.selectedWidgets.length > 0) {
                yield put({
                    type: 'editor/setState',
                    payload: {
                        selectedWidget: editor.selectedWidget && editor.selectedWidget.widget_id === widget.widget_id ? widget : editor.selectedWidget,
                        selectedWidgets: editor.selectedWidgets.map((w) => {
                            if (w.widget_id === widget.widget_id) return { ...w, ...widget };
                            else return w;
                        }),
                    },
                });
            }
        },
        *updateWidgets({ payload: widgets }, { select, call, put }) {
            const oldWidgets = yield select(state => state.widgets);
            const editor = yield select(state => state.editor);
            // 记录所有需要修改的key值
            const widgetIds = {};
            const objWidgets = {};
            for (let i = 0; i < widgets.length; i++) {
                widgetIds[widgets[i].widget_id] = i + 1;
            }
            // 修改
            for (let i = 0; i < oldWidgets.length; i++) {
                const tWidgetId = oldWidgets[i].widget_id;
                if (widgetIds[tWidgetId] !== undefined) {
                    const index = widgetIds[tWidgetId] - 1;
                    oldWidgets[i] = { ...oldWidgets[i], ...widgets[index], timestamp: Math.round(new Date().valueOf() / 1000) + Math.random() };
                }
                objWidgets[tWidgetId] = oldWidgets[i];
            }
            yield put({
                type: 'save',
                payload: oldWidgets,
            });
            // 更新selselectedWidget 和 selectedWidgets
            if (editor.selectedWidgets.length > 0) {
                yield put({
                    type: 'editor/setState',
                    payload: {
                        selectedWidget: editor.selectedWidget && widgetIds[editor.selectedWidget.widget_id] ? objWidgets[tWidgetId] : editor.selectedWidget,
                        selectedWidgets: editor.selectedWidgets.map((w) => {
                            if (widgetIds[w.widget_id]) return { ...w, ...objWidgets[w.widget_id] };
                            else return w;
                        }),
                    },
                });
            }
        },
    },
    subscriptions: {

    },
};
